package com.payment.ktb.utils;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.flyco.animation.BaseAnimatorSet;
import com.flyco.animation.BounceEnter.BounceTopEnter;
import com.flyco.animation.SlideExit.SlideBottomExit;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.MaterialDialog;
import com.payment.ktb.Interface.HttpCallbackListener;
import com.payment.ktb.R;
import com.payment.ktb.constants.Constants;
import com.payment.ktb.constants.ConstantsUser;
import com.payment.ktb.constants.HttpActions;
import com.payment.ktb.constants.HttpUrls;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

/**
 * Created by syd on 2016/7/13.
 */
public class UpdateAPKUtils {


    private static String updateMsg;
    private static String downloadUrl;
    private static String isUpd;
    private static String updateFlg;
    private static String versionCode;
    private static Context mContext;
    static ProgressDialogUtils progressDialogUtils = null;
    static RequestQueue mQueue;
    private static File apkFile;


    /* 更新进度条 */
    private static BaseAnimatorSet mBasIn = new BounceTopEnter();
    private static BaseAnimatorSet mBasOut = new SlideBottomExit();
    /* 下载保存路径 */
    private static String mSavePath;
    private static String apkName = "jnsh.apk";
    /* 记录进度条数量 */
    private static int progress;
    /* 下载中 */
    private static final int DOWNLOAD = 1;
    /* 下载结束 */
    private static final int DOWNLOAD_FINISH = 2;
    private static UpdateAPKUtils mUpdateAPKUtils;

    /**
     * 初始化升级
     * @param context
     */
    public static UpdateAPKUtils getInstance(Context context,String downloadUrlExtra) {

            mContext = context;
            downloadUrl = downloadUrlExtra;
            progressDialogUtils = new ProgressDialogUtils(mContext);
            mQueue = Volley.newRequestQueue(mContext);
            mUpdateAPKUtils = new UpdateAPKUtils();
            return mUpdateAPKUtils;}


        public static UpdateAPKUtils getInstance(Context context) {

            mContext = context;
            progressDialogUtils = new ProgressDialogUtils(mContext);
            mQueue = Volley.newRequestQueue(mContext);
            mUpdateAPKUtils = new UpdateAPKUtils();
            return mUpdateAPKUtils;
    }

    /**
     *检测升级
     */
    public static void updateCheck(final Context Context) {
        getInstance(Context);
        progressDialogUtils.showProgress();
        //构造传输参数
        String os = "ANDROID";
        String version = String.valueOf(DeviceUtils.getVersionCode());
        String token = SharedPreferencesUtils.getString(ConstantsUser.userToken);
        //MD5
        String sign = Md5Utils.md5Hex(os + version + SharedPreferencesUtils.getString(ConstantsUser.userKey));
        //将参数放入map中
        HashMap<String, String> map = new HashMap<String,String>();
        map.put("os",os);
        map.put("version",version);
        map.put("token",token);
        map.put("sign",sign);

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.shopSdkVersionState, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {

                progressDialogUtils.dismissProgress();

                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String code = jsonObject.optString("code");
                    if (Constants.NORMAL_CODE.equals(code)) {

                        isUpd = jsonObject.optString("isUpd");
                        updateFlg = jsonObject.optString("updateFlg");
                        versionCode = jsonObject.optString("versionCode");
                        updateMsg = jsonObject.optString("updateMsg");
                        downloadUrl = jsonObject.optString("downloadUrl");
                        if ("1".equals(isUpd)) {
                            updateDialog();
                        }
                    } else {
                        AlertDialogUtils.showAlertDialog(mContext, jsonObject.optString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, mContext.getResources().getString(R.string.json_parse_error));
                }
            }
            @Override
            public void onError(VolleyError volleyError) {
                progressDialogUtils.dismissProgress();
                AlertDialogUtils.showAlertDialog(mContext, mContext.getResources().getString(R.string.fail_to_connect_server));
            }
        });


    }



    private static void updateDialog() {

        final MaterialDialog dialog = new MaterialDialog(mContext);
        dialog.content(
                updateMsg)//
                .title("已发现新版本")
                .btnText("取消", "更新")//
                .showAnim(mBasIn)//
                .dismissAnim(mBasOut)//
                .show();

        dialog.setOnBtnClickL(
                new OnBtnClickL() {//left btn click listener
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                    }
                },
                new OnBtnClickL() {//right btn click listener
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                        downloadApk();
                    }
                }
        );
    }



    /**
     * 下载apk文件
     */
    public static void downloadApk()
    {
        // 启动新线程下载软件
        new downloadApkThread().start();
    }





    /**
     * 下载文件线程
     */
    public static class downloadApkThread extends Thread
    {
        @Override
        public void run()
        {
            try
            {
                // 判断SD卡是否存在，并且是否具有读写权限
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    // 获得存储卡的路径
                    String sdpath = Environment.getExternalStorageDirectory() + "/";
                    mSavePath = sdpath + "download";
                    URL url = new URL(downloadUrl);
                    // 创建连接
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    // 获取文件大小
                    int length = conn.getContentLength();
                    // 创建输入流
                    InputStream is = conn.getInputStream();

                    File file = new File(mSavePath);
                    // 判断文件目录是否存在
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    apkFile = new File(mSavePath, apkName);
                    FileOutputStream fos = new FileOutputStream(apkFile);
                    int count = 0;
                    int numread = 0;
                    // 缓存
                    byte buf[] = new byte[1024];
                    // 写入到文件中
                    while ((numread = is.read(buf)) != -1) {
                        count += numread;
                        // 计算进度条位置
                        progress = (int) (((float) count / length) * 100);
                        // 更新进度
                        mHandler.sendEmptyMessage(DOWNLOAD);
                        // 写入文件
                        fos.write(buf, 0, numread);
                    }
                    mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                    fos.close();
                    is.close();
                } else {
                    ToastUtils.showToast("请下载最新版本进行更新！");
                }
            } catch (MalformedURLException e)
            {
                e.printStackTrace();
            } catch (IOException e)
            {
                e.printStackTrace();
            }

        }
    };


    /**
     * 处理现在apk的状态
     */
    private static Handler mHandler = new Handler()
    {
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                // 正在下载
                case DOWNLOAD:
                    // 设置进度条位置
                    progressDialogUtils.showProgress("已下载 " + progress + "%");
                    break;
                case DOWNLOAD_FINISH:
                    progressDialogUtils.dismissProgress();
                    // 安装文件
                    installApk();
                    break;
                default:
                    break;
            }
        };
    };


    /**
     * 安装APK文件
     */
    private static void installApk()
    {
        File apkFile = new File(mSavePath, apkName);
        if (!apkFile.exists())
        {
            return;
        }
        // 通过Intent安装APK文件
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setDataAndType(Uri.parse("file://" + apkFile.toString()), "application/vnd.android.package-archive");
        mContext.startActivity(i);
        SharedPreferencesUtils.putBoolean(Constants.GOGUIDEACTIVITY,true);
    }


}
